package com.sg.zwfw.httpServer;

import com.sg.zwfw.utils.Signature;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.util.Date;

/**
 * 基于OkHttp的demo
 */
public class DemoHttpclient {

    public String callApiGateway(String paasId, String paasToken, String apiPath, String serverUrl) {
        // 各种参数
//        String paasId = "";// 你的paasId
//        String paasToken = "";// 你的paasToken
//
//        String apiPath = "";// 接口地址

//        String serverUrl = ""; // 域名或ip

        long now = new Date().getTime();
        String timestamp = Long.toString((long) Math.floor(now / 1000));
        String nonce = Long.toHexString(now) + "-" + Long.toHexString((long) Math.floor(Math.random() * 0xFFFFFF));
        String signature = null;
        try {
            signature = Signature.toSHA256(timestamp + paasToken + nonce + timestamp);
            // 创建CloseableHttpClient
            CloseableHttpClient client = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(serverUrl + apiPath);
            System.out.println(httpPost);
            httpPost.setHeader("x-tif-paasid", paasId);
            httpPost.setHeader("x-tif-timestamp", timestamp);
            httpPost.setHeader("x-tif-signature", signature);
            httpPost.setHeader("x-tif-nonce", nonce);
            httpPost.setHeader("Content-Type", "application/json");

            CloseableHttpResponse response = client.execute(httpPost);
//            System.out.println(EntityUtils.toString(response.getEntity()));
            return EntityUtils.toString(response.getEntity());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
